package io.renren.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.renren.dao.*;
import io.renren.entity.*;
import io.renren.entity.VO.PersonDispatchEntityVO;
import io.renren.service.BaseService;
import io.renren.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

import io.renren.service.PersonDispatchService;
import org.springframework.transaction.annotation.Transactional;


@Service("personDispatchService")
public class PersonDispatchServiceImpl extends BaseService implements PersonDispatchService {
    @Autowired
    private PersonDispatchDao personDispatchDao;
    @Autowired
    private CustomSettlementDao customSettlementDao;
    @Autowired
    private SocialSecurityAreaBasicDao socialSecurityAreaBasicDao;
    @Autowired
    private SocialSecurityAreaTenetDao socialSecurityAreaTenetDao;
    @Autowired
    private EmpBaseinfoDao empBaseinfoDao;
    @Autowired
    private SocialSecurityTransactionDao socialSecurityTransactionDao;
    @Autowired
    private SocialSecurityPersonBasicDao socialSecurityPersonBasicDao;
    @Autowired
    private ServiceSettlementDetailDao serviceSettlementDetailDao;
    @Autowired
    private CustomContractDao customContractDao;
    @Autowired
    private ServiceSettlementMainDao serviceSettlementMainDao;
    @Autowired
    private SocialSecurityPayDetailDao socialSecurityPayDetailDao;
    @Autowired
    private SalaryBasicinfoDao salaryBasicinfoDao;

    @Override
    @Transactional
    public int confirm(JSONObject jsonObject) {
        int res = 0;
        Calendar ca = Calendar.getInstance();
        int year = ca.get(Calendar.YEAR);
        int month = ca.get(Calendar.MONTH)+1;
        Map<String, Object> map = new HashMap<>();
        map.put("year",year);
        map.put("month",month);
        //SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date date = jsonObject.getDate("entryDate");
        //String time = format.format(confirmdate);
        SysUserEntity user = (SysUserEntity)jsonObject.get("user");
        /*Date date = null;
        try {
            date = format.parse(time);
            System.out.println(date + "" + date.getClass());
        } catch (ParseException e) {
            res = 1;
            e.printStackTrace();
        }*/
        String idss = jsonObject.getString("ids");
        String[] ids = idss.substring(1,idss.length()-1).split(",");
        for (Object id : ids) {
            id = id.toString().substring(1,id.toString().length()-1);
            //获取人员派遣表数据
            PersonDispatchEntity person = personDispatchDao.queryObject(id);
            if(!"dispatchstatus01".equals(person.getDispatchStatus())){
                logger.info("info","【"+person.getId()+"】记录为非未确认记录，不能派遣！");
                continue;//跳出本次循环，继续执行下一条循环
            }
            person.setEntryDate(date);
            person.setDispatchType(jsonObject.getString("dispatchType"));
            person.setDepartment(jsonObject.getString("department"));
            person.setStation(jsonObject.getString("station"));
            person.setDispatchStatus("dispatchstatus02");
            update(person);
            //获取员工所属的结算点信息
            CustomSettlementEntity settlement = customSettlementDao.queryObject(person.getSettlementId());
            //通过结算点配置的区域编号来获取社保区域基数信息
            map.put("index",settlement.getAreaBaseId());
            SocialSecurityAreaBasicEntity areaBasic = socialSecurityAreaBasicDao.getAreaBasicByIndex(map);//.queryObject(settlement.getAreaBaseId());
            if(areaBasic==null){
                res = 1;
                return res;
            }
            //获取社保的数据字典
            List<HashMap<String, Object>> list = empBaseinfoDao.getSelectInfo("socialSecurity");
            //获取员工基本信息
            EmpBaseinfoEntity empBaseinfoEntity = empBaseinfoDao.queryObject(person.getPersonId());

            //定义社保个人基数表对象
            SocialSecurityPersonBasicEntity ssperson = new SocialSecurityPersonBasicEntity();
            Class areaBasicClass = areaBasic.getClass();
            Field[] fs = areaBasicClass.getDeclaredFields();
            for (Field f : fs) {
                f.setAccessible(true);
                String name = f.getName();
                Object val = null;
                try {
                    val = f.get(areaBasic);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                Class sspersonClass = ssperson.getClass();
                Field[] fsssperson = sspersonClass.getDeclaredFields();
                for (Field field : fsssperson) {
                    field.setAccessible(true);
                    String ssname = field.getName();
                    if (!ssname.equals("id")&&!ssname.equals("serialVersionUID")) {
                        if (ssname.equals(name)) {
                            System.out.print(name);
                            //ssname = ssname.substring(0,1).toUpperCase()+ssname.substring(1);
                            try {
                                field.set(ssperson, val);
                                break;
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                        }

                    }
                }
            }
            ssperson.setName(empBaseinfoEntity.getName());
            ssperson.setEmpid(Integer.valueOf(person.getPersonId()));
            ssperson.setSettlementid(person.getSettlementId());
            ssperson.setSettlementname(settlement.getSettlementName());
            //生成本年度的个人社保基数表数据
            for(int i = month; i <= 12; i++){
                ssperson.setMonth(i+"");
                ssperson.setYear(year+"");
                socialSecurityPersonBasicDao.saveByDynamicCol(ssperson);
            }

            //社保申报状态(0，待申报,1,申报中，2，已申报，3，退回,4，不申报,5,重新申报，6，临时退保)
            //审核状态(0，未审核，1,初审，2,终审，3，反审，4，退回)
            if ("0".equals(areaBasic.getIstotal())) {
                for (HashMap<String, Object> m : list) {
                    SocialSecurityTransactionEntity trans = new SocialSecurityTransactionEntity();
                    String ssvalue = m.get("label").toString();
                    //0表示自动申报
                    if ("养老保险".equals(ssvalue)) {
                        if ("0".equals(settlement.getPensionDeclar())) {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"0");
                        } else {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"1");
                        }
                    } else if ("工伤保险".equals(ssvalue)) {
                        if ("0".equals(settlement.getInjuryDeclar())) {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"0");
                        } else {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"1");
                        }
                    } else if ("失业保险".equals(ssvalue)) {
                        if ("0".equals(settlement.getUnemploymentDeclar())) {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"0");
                        } else {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"1");
                        }
                    } else if ("医疗保险".equals(ssvalue)) {
                        if ("0".equals(settlement.getMedicareClar())) {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"0");
                        } else {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"1");
                        }
                    } else if ("生育保险".equals(ssvalue)) {
                        if ("0".equals(settlement.getMaternityClar())) {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"0");
                        } else {
                            generaterSSTrans(trans,user,date,person,m.get("value").toString(),"1");
                        }
                    }
                }
            } else {
                SocialSecurityTransactionEntity trans = new SocialSecurityTransactionEntity();
                trans.setEmployId(Integer.valueOf(person.getPersonId()));
                trans.setUnitId(person.getSettlementId());
                trans.setId(person.getId());
                trans.setDeclareType("declare01");  //declare01,申报;declare02,退保
                trans.setInsuranceType("socialSecurity06");//五险合一
                trans.setDeclareDate(date);
                trans.setDeclarePerson(user.getUsername());
                trans.setEmploymentForm("");
                trans.setTransactionReason("新用户审核");
                trans.setPersonDispatchId(person.getId()+"");
                if ("0".equals(settlement.getMaternityClar())) {
                    System.out.print("");
                    trans.setTrialJudge(user.getUsername());
                    trans.setTrialDate(date);
                    trans.setConfirmStatus("1");
                } else {
                    trans.setConfirmStatus("0");
                }
                socialSecurityTransactionDao.saveByDynamicCol(trans);
            }
        }
        return res;
    }

    /**
     *
     * @param trans  社保异动对象
     * @param user   登录用户
     * @param date   审核时间
     * @param person 人员派遣表数据对象
     * @param value  社保类型字典数据
     * @param type   是否主动申报状态(0,主动申报,1,手动申报)
     */
    private void generaterSSTrans(SocialSecurityTransactionEntity trans, SysUserEntity user, Date date, PersonDispatchEntity person, String value, String type){
        if(type.equals("0")){
            trans.setTrialJudge(user.getUsername());
            trans.setTrialDate(date);
            trans.setConfirmStatus("1");
            trans.setProcessStatus("1");
        }else{
            trans.setConfirmStatus("0");
            trans.setProcessStatus("0");
        }

        trans.setEmployId(Integer.valueOf(person.getPersonId()));
        trans.setUnitId(person.getSettlementId());
        trans.setId(person.getId());
        trans.setDeclareType("declare01");  //declare01,申报;declare02,退保
        trans.setInsuranceType(value);
        trans.setDeclareDate(date);
        trans.setDeclarePerson(user.getUsername());
        trans.setEmploymentForm("");
        trans.setTransactionReason("新用户审核");
        trans.setPersonDispatchId(person.getId()+"");
        socialSecurityTransactionDao.saveByDynamicCol(trans);
    }

    @Override
    public PersonDispatchEntity queryObject(String id) {
        return personDispatchDao.queryObject(id);
    }

    @Override
    public List<PersonDispatchEntityVO> queryList(Map<String, Object> map) {
        return personDispatchDao.queryListBySettlementid(map);
        //return personDispatchDao.queryList(map);
    }

    @Override
    public int queryTotal(Map<String, Object> map) {
        return personDispatchDao.queryTotal(map);
    }

    @Override
    public void save(PersonDispatchEntity personDispatch) {
        personDispatchDao.save(personDispatch);
    }

    @Override
    public void update(PersonDispatchEntity personDispatch) {
        personDispatchDao.update(personDispatch);
    }

    @Override
    public void delete(String id) {
        personDispatchDao.delete(id);
    }

    @Override
    public void deleteBatch(String[] ids) {
        personDispatchDao.deleteBatch(ids);
    }

    @Override
    public List<Map<String, Object>> queryListByIds(Integer[] ids) {
        return personDispatchDao.queryListByIds(ids);
    }

    /**
     * 结算单
     *
     * @param params
     */
    @Override
    public List<ServiceSettlementDetailEntity> statement(Map<String, Object> params) {
        List<ServiceSettlementDetailEntity> res = new ArrayList<>();
        if(params.get("settlementid")==null){
            return null;
        }
        String settlementid = params.get("settlementid").toString();
        System.out.println("settlementid:" + settlementid);
        String year = params.get("year").toString();
        String month = params.get("month").toString();
        String batch = params.get("batch").toString();
        List<PersonDispatchEntity> list = personDispatchDao.getEmpListBySettlementid(settlementid);
        CustomSettlementEntity settlement = customSettlementDao.queryObject(settlementid);
        List<CustomContractEntity> contract = customContractDao.getContractByContractNO(settlement.getContractNo());
        if(contract == null){
            logger.info("info","当前结算点没有有效合同！");
            return null;
        }
        int i = 1;
        for (PersonDispatchEntity ps : list) {
            String empid = ps.getPersonId();
            Map<String, Object> map = new HashMap<>();
            map.put("year", year);
            map.put("month", month);
            map.put("empid", empid);

            List<SocialSecurityPayDetailEntity> payDetailList = socialSecurityPayDetailDao.getPersonPayDetail(map);

            //SocialSecurityPersonBasicEntity ssperson = socialSecurityPersonBasicDao.getSocialSecurityPersonBasicInfo(map);
            EmpBaseinfoEntity empbase = empBaseinfoDao.queryObject(empid);
            if(empbase==null){
                continue;
            }
            ServiceSettlementDetailEntity ssDetail = new ServiceSettlementDetailEntity();
            ssDetail.setEmpid(Integer.valueOf(empid));
            ssDetail.setSettlementid(settlementid);
            ssDetail.setEmpstatus(ps.getEnable().toString());
            ssDetail.setDepartment(ps.getDepartment());
            if(!StringUtils.isBlank(empbase.getName())){
                ssDetail.setName(empbase.getName());
            }
            ssDetail.setCardno(empbase.getIdno());
            ssDetail.setYear(year);
            ssDetail.setMonth(month);
            ssDetail.setBatch(Integer.valueOf(batch));

            for (SocialSecurityPayDetailEntity pay : payDetailList) {
                String sstype = pay.getSocialSecurityType();
                if ("socialSecurity01".equals(sstype)) {//养老保险
                    //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                    ssDetail.setDwyjYanglYs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setGryjYanglYs(pay.getPersonPayable() - pay.getPersonPay());

                    ssDetail.setJsdwYanglSs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrYanglSs(pay.getPersonPayable() - pay.getPersonPay());
                } else if ("socialSecurity02".equals(sstype)) {//生育保险
                    ssDetail.setDwyjShengyYs(pay.getUnitPayable() - pay.getUnitPay());

                    ssDetail.setJsdwShengySs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrShengySs(pay.getPersonPayable() - pay.getPersonPay());
                } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                    ssDetail.setDwyjGongsYs(pay.getUnitPayable() - pay.getUnitPay());

                    ssDetail.setJsdwGongsSs(pay.getUnitPayable() - pay.getUnitPay());
                } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                    ssDetail.setDwyjYilYs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setGryjYilYs(pay.getPersonPayable() - pay.getPersonPay());

                    ssDetail.setJsdwYilSs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrYilSs(pay.getPersonPayable() - pay.getPersonPay());
                } else if ("socialSecurity05".equals(sstype)) {//失业保险
                    ssDetail.setDwyjShiyYs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setGryjShiyYs(pay.getPersonPayable() - pay.getPersonPay());

                    ssDetail.setJsdwShiySs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrShiySs(pay.getPersonPayable() - pay.getPersonPay());
                } else if ("socialSecurity07".equals(sstype)) {//大病保险
                    ssDetail.setDwyjDabYs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setGryjDabYs(pay.getPersonPayable() - pay.getPersonPay());

                    ssDetail.setJsdwDabSs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrDabSs(pay.getPersonPayable() - pay.getPersonPay());
                } else if ("socialSecurity08".equals(sstype)) {//公积金
                    ssDetail.setDwyjGongjjYs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setGryjGongjjYs(pay.getPersonPayable() - pay.getPersonPay());

                    ssDetail.setJsdwGongjjSs(pay.getUnitPayable() - pay.getUnitPay());
                    ssDetail.setJsgrGongjjSs(pay.getPersonPayable() - pay.getPersonPay());
                }
            }

            /**
             * 管理费，从合同数据中获取，数据暂时没有同步，先屏蔽
             */
            //ssDetail.setJsdwGuanlifSs(Double.valueOf(contract.get(0).getPercentormoney()));

            ssDetail.setId(i);
            i++;
            //计算合计字段
            ssDetail = ServiceSettlementReflect(ssDetail);
            res.add(ssDetail);
        }

        Map<String, Object> m = new HashMap<>();
        m.put("settlementid", settlementid);
        //获取补报数据
        List<SocialSecurityPayDetailEntity> BBpayDetailList = socialSecurityPayDetailDao.getBBPayDetail(m);
        Map<String, Object> bblist = BcOrBb(BBpayDetailList, "bb", batch, i);
        res.addAll((List<ServiceSettlementDetailEntity>) bblist.get("list"));
        //获取补差数据
        List<SocialSecurityPayDetailEntity> BCpayDetailList = socialSecurityPayDetailDao.getBCPayDetail(m);
        Map<String, Object> bclist = BcOrBb(BCpayDetailList, "bc", batch, Integer.valueOf(bblist.get("index").toString()));
        res.addAll((List<ServiceSettlementDetailEntity>) bclist.get("list"));
        return res;
    }

    /**
     * 结算单补差或补报
     *
     * @param BCpayDetailList
     * @param type
     */
    public Map<String, Object> BcOrBb(List<SocialSecurityPayDetailEntity> BCpayDetailList, String type, String batch, int i) {
        List<ServiceSettlementDetailEntity> res = new ArrayList<>();

        //数组分组
        Map<String, List<SocialSecurityPayDetailEntity>> m = groupArray(BCpayDetailList);

        Set<String> set = m.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            ServiceSettlementDetailEntity ssDetail = new ServiceSettlementDetailEntity();
            List<SocialSecurityPayDetailEntity> l = m.get(it.next());
            SocialSecurityPayDetailEntity ss = l.get(0);
            EmpBaseinfoEntity empbase = empBaseinfoDao.queryObject(ss.getEmpid());
            PersonDispatchEntity ps = personDispatchDao.getPersonDispatchByEmpid(ss.getEmpid() + "");
            ssDetail.setEmpid(ss.getEmpid());
            ssDetail.setEmpstatus(ps.getEnable().toString());
            ssDetail.setDepartment(ps.getDepartment());
            ssDetail.setName(empbase.getName());
            ssDetail.setCardno(empbase.getIdno());
            ssDetail.setYear(ss.getYear() + "");
            ssDetail.setMonth(ss.getMonth() + "");
            ssDetail.setBatch(Integer.valueOf(batch));

            for (SocialSecurityPayDetailEntity pay : l) {
                String sstype = pay.getSocialSecurityType();
                if ("bc".equals(type)) {
                    if ("socialSecurity01".equals(sstype)) {//养老保险
                        //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                        ssDetail.setBcdwYanglYs(pay.getBalancePayableUnit() - pay.getBalancePayUnit());
                        ssDetail.setBcgrYanglYs(pay.getBalancePayablePerson() - pay.getBalancePayPerson());
                    } else if ("socialSecurity02".equals(sstype)) {//生育保险
                        ssDetail.setBcdwShengyYs(pay.getBalancePayableUnit() - pay.getBalancePayUnit());
                        ssDetail.setBcgrShengyYs(pay.getBalancePayablePerson() - pay.getBalancePayPerson());
                    } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                        ssDetail.setBcdwGongsYs(pay.getBalancePayableUnit() - pay.getBalancePayUnit());
                        ssDetail.setBcgrGongsYs(pay.getBalancePayablePerson() - pay.getBalancePayPerson());
                    } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                        ssDetail.setBcdwYilYs(pay.getBalancePayableUnit() - pay.getBalancePayUnit());
                        ssDetail.setBcgrYilYs(pay.getBalancePayablePerson() - pay.getBalancePayPerson());
                    } else if ("socialSecurity05".equals(sstype)) {//失业保险
                        ssDetail.setBcdwShiyYs(pay.getBalancePayableUnit() - pay.getBalancePayUnit());
                        ssDetail.setBcgrShiyYs(pay.getBalancePayablePerson() - pay.getBalancePayPerson());
                    }
                } else {
                    if ("socialSecurity01".equals(sstype)) {//养老保险
                        //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                        ssDetail.setDwyjYanglYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setGryjYanglYs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());

                        ssDetail.setJsdwYanglSs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrYanglSs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    } else if ("socialSecurity02".equals(sstype)) {//生育保险
                        ssDetail.setDwyjShengyYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());

                        ssDetail.setJsdwShengySs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrShengySs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                        ssDetail.setDwyjGongsYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());

                        ssDetail.setJsdwGongsSs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                    } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                        ssDetail.setDwyjYilYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setGryjYilYs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());

                        ssDetail.setJsdwYilSs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrYilSs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    } else if ("socialSecurity05".equals(sstype)) {//失业保险
                        ssDetail.setDwyjShiyYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setGryjShiyYs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());

                        ssDetail.setJsdwShiySs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrShiySs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    } else if ("socialSecurity07".equals(sstype)) {//大病保险
                        ssDetail.setDwyjDabYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setGryjDabYs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());

                        ssDetail.setJsdwDabSs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrDabSs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    } else if ("socialSecurity08".equals(sstype)) {//公积金
                        ssDetail.setDwyjGongjjYs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setGryjGongjjYs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());

                        ssDetail.setJsdwGongjjSs(pay.getBubaoPayableUnit() - pay.getBubaoPayUnit());
                        ssDetail.setJsgrGongjjSs(pay.getBubaoPayablePerson() - pay.getBubaoPayPerson());
                    }
                }

            }
            ssDetail.setId(i);
            i++;
            //计算合计字段
            ssDetail = ServiceSettlementReflect(ssDetail);
            res.add(ssDetail);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("list", res);
        result.put("index", i);
        return result;
    }

    @Override
    @Transactional
    public void saveStatementDetail(JSONArray jsonArray) {

        ServiceSettlementMainEntity ssMain = new ServiceSettlementMainEntity();

        Class ssmClass = ssMain.getClass();
        Field[] ssmfs = ssmClass.getDeclaredFields();
        for (Object o : jsonArray) {
            JSONObject obj = (JSONObject) o;
            ServiceSettlementDetailEntity ssDetail = obj.toJavaObject(ServiceSettlementDetailEntity.class);
            //计算合计字段
            ssDetail = ServiceSettlementReflect(ssDetail);

            ssMain.setYear(ssDetail.getYear());
            ssMain.setMonth(ssDetail.getMonth());
            ssMain.setBatch(ssDetail.getBatch());
            ssMain.setSettlementid(ssDetail.getSettlementid());
            Class ssdClass = ssDetail.getClass();
            Field[] ssdfs = ssdClass.getDeclaredFields();
            for (Field ssdf : ssdfs) {
                ssdf.setAccessible(true);
                String name = ssdf.getName();
                Object val = null;
                try {
                    val = ssdf.get(ssDetail);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

                for (Field ssmf : ssmfs) {
                    ssmf.setAccessible(true);
                    String ssmname = ssmf.getName();

                    if (ssmf.getGenericType().toString().equals("class java.lang.Double")) {
                        if (ssmname.equals(name)) {
                            Object ssmval = null;
                            try {
                                ssmval = ssmf.get(ssMain);
                                if (val != null) {
                                    /**
                                     * 结算单汇总表，如果遇到结算单位和结算个人实收的数据，比如五险一金。
                                     * 这时候需要统计各项缴费的人数
                                     */
                                    if (ssmname.contains("jsdw") || ssmname.contains("jsgr")) {
                                        String methodname = ssmname.substring(0, 1).toUpperCase() + ssmname.substring(1) + "Rs";
                                        Method m = ssmClass.getMethod("get" + methodname);
                                        Integer rsval = m.invoke(ssMain) == null ? 0 : Integer.valueOf(m.invoke(ssMain).toString());

                                        Class[] parameterTypes = new Class[1];
                                        Field field = ssmClass.getDeclaredField(ssmname + "Rs");
                                        parameterTypes[0] = field.getType();

                                        m = ssmClass.getMethod("set" + methodname, parameterTypes);
                                        m.invoke(ssMain, rsval + 1);
                                    }
                                    ssmf.set(ssMain, Double.valueOf(val.toString()) + Double.valueOf(ssmval == null ? "0" : ssmval.toString()));
                                }
                                //ssmf.set(ssMain, Double.valueOf(val==null?"0":val.toString())+Double.valueOf(ssmval==null?"0":ssmval.toString()));
                                break;
                            } catch (IllegalAccessException e) {
                                e.printStackTrace();
                            } catch (NoSuchMethodException e) {
                                e.printStackTrace();
                            } catch (InvocationTargetException e) {
                                e.printStackTrace();
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
        serviceSettlementMainDao.saveByDynamicCol(ssMain);

        for (Object o : jsonArray) {
            JSONObject obj = (JSONObject) o;
            ServiceSettlementDetailEntity ssDetail = obj.toJavaObject(ServiceSettlementDetailEntity.class);
            ssDetail.setId(null);
            ssDetail.setSsmid(ssMain.getId());
            serviceSettlementDetailDao.saveByDynamicCol(ssDetail);
        }
    }

    public ServiceSettlementDetailEntity ServiceSettlementReflect(ServiceSettlementDetailEntity ssDetail) {
        double total = 0;
        double jsdwsubtotal = 0;
        double jsgrsubtotal = 0;
        Class ssClass = ssDetail.getClass();
        Field[] fs = ssClass.getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            String name = f.getName();
            Object val = null;
            try {
                val = f.get(ssDetail);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            if (name.contains("Ss") && !name.equals("jsdwUnitsubtotalSs")
                    && !name.equals("jsgrPersonsubtotalSs")) {
                total += Double.valueOf(val == null ? "0" : val.toString());
            }
            if (name.contains("jsdw") && !name.equals("jsdwUnitsubtotalSs")) {
                jsdwsubtotal += Double.valueOf(val == null ? "0" : val.toString());
            }
            if (name.contains("jsgr") && !name.equals("jsgrPersonsubtotalSs")) {
                jsgrsubtotal += Double.valueOf(val == null ? "0" : val.toString());
            }
        }
        ssDetail.setTotalPaid(total);
        ssDetail.setJsdwUnitsubtotalSs(jsdwsubtotal);
        ssDetail.setJsgrPersonsubtotalSs(jsgrsubtotal);
        return ssDetail;
    }

    @Override
    public List<SalaryBasicinfoEntity> salary(Map<String, Object> params) {
        List<SalaryBasicinfoEntity> res = new ArrayList<>();
        if(params.get("settlementid")==null){
            return null;
        }
        String settlementid = params.get("settlementid").toString();
        System.out.println("settlementid:" + settlementid);
        String year = params.get("year").toString();
        String month = params.get("month").toString();
        String batch = params.get("batch").toString();
        String ym = year + "-" + month;
        List<ServiceSettlementDetailEntity> ssDetailList = serviceSettlementDetailDao.getServiceSettlemetnByPatch(params);
        if (ssDetailList == null || ssDetailList.size() == 0) {
            return null;
        }
        int i = 1;
        for (ServiceSettlementDetailEntity ssDetail : ssDetailList) {
            String ssym = ssDetail.getYear() + "-" + ssDetail.getMonth();
            if (ym.equals(ssym)) {
                SalaryBasicinfoEntity sbEntity = new SalaryBasicinfoEntity();
                sbEntity.setId(i);
                sbEntity.setSettlementid(settlementid);
                sbEntity.setStatus("0");
                sbEntity.setYear(year);
                sbEntity.setMonth(month);
                sbEntity.setEmpid(ssDetail.getEmpid());
                EmpBaseinfoEntity empbase = empBaseinfoDao.queryObject(ssDetail.getEmpid());
                sbEntity.setBatch(ssDetail.getBatch());
                sbEntity.setEmpname(empbase.getName());
                sbEntity.setCardno(empbase.getIdno());

                sbEntity.setYfgzSalary(ssDetail.getJsdwSalarySs());
                sbEntity.setYfgzOuttimepay(ssDetail.getJsdwOvertimepaySs());

                params.put("empid", ssDetail.getEmpid());
                List<SocialSecurityPayDetailEntity> payDetailList = socialSecurityPayDetailDao.getPersonPayDetail(params);
                for (SocialSecurityPayDetailEntity payDetail : payDetailList) {
                    String sstype = payDetail.getSocialSecurityType();
                    if ("socialSecurity01".equals(sstype)) {//养老保险
                        //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                        sbEntity.setSbgrYangl(payDetail.getPersonPayable());
                    } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                        sbEntity.setSbgrGongs(payDetail.getPersonPayable());
                    } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                        sbEntity.setSbgrYil(payDetail.getPersonPayable());
                    } else if ("socialSecurity05".equals(sstype)) {//失业保险
                        sbEntity.setSbgrShiy(payDetail.getPersonPayable());
                    } else if ("socialSecurity07".equals(sstype)) {//大病保险
                        sbEntity.setSbgrDab(payDetail.getPersonPayable());
                    } else if ("socialSecurity08".equals(sstype)) {//公积金
                        sbEntity.setSbgrGongjjZc(payDetail.getPersonPayable());
                    }
                }
                res.add(sbEntity);
                i++;
            }
        }

        //获取补报补差数据
        Map<String, Object> m = new HashMap<>();
        m.put("settlementid", settlementid);
        //获取补报数据
        List<SocialSecurityPayDetailEntity> BBpayDetailList = socialSecurityPayDetailDao.getBBPayDetail(m);
        Map<String, Object> bblist = BcOrBb(BBpayDetailList, "bb", batch, i);
        res.addAll((List<SalaryBasicinfoEntity>)bblist.get("list"));
        //获取补差数据
        List<SocialSecurityPayDetailEntity> BCpayDetailList = socialSecurityPayDetailDao.getBCPayDetail(m);
        Map<String, Object> bclist = BcOrBb(BCpayDetailList, "bc", batch, Integer.valueOf(bblist.get("index").toString()));
        res.addAll((List<SalaryBasicinfoEntity>)bclist.get("list"));
        return res;
    }

    /**
     * 工资补差或补报
     *
     * @param BCpayDetailList
     * @param type
     */
    public Map<String, Object> SalaryBcOrBb(List<SocialSecurityPayDetailEntity> BCpayDetailList, String type, String batch, int i) {
        List<SalaryBasicinfoEntity> res = new ArrayList<>();

        //数组分组
        Map<String, List<SocialSecurityPayDetailEntity>> m = groupArray(BCpayDetailList);

        Set<String> set = m.keySet();
        Iterator<String> it = set.iterator();
        while (it.hasNext()) {
            List<SocialSecurityPayDetailEntity> l = m.get(it.next());
            SocialSecurityPayDetailEntity ss = l.get(0);

            SalaryBasicinfoEntity sbEntity = new SalaryBasicinfoEntity();

            sbEntity.setId(i);
            sbEntity.setSettlementid(ss.getUnitId());
            sbEntity.setStatus("0");
            sbEntity.setYear(ss.getYear() + "");
            sbEntity.setMonth(ss.getMonth() + "");
            sbEntity.setEmpid(ss.getEmpid());
            EmpBaseinfoEntity empbase = empBaseinfoDao.queryObject(ss.getEmpid());
            sbEntity.setBatch(Integer.valueOf(batch));
            sbEntity.setEmpname(empbase.getName());
            sbEntity.setCardno(empbase.getIdno());

            for (SocialSecurityPayDetailEntity payDetail : l) {
                String sstype = payDetail.getSocialSecurityType();
                if ("bb".equals(type)) {
                    if ("socialSecurity01".equals(sstype)) {//养老保险
                        //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                        sbEntity.setSbgrYangl(payDetail.getBubaoPayablePerson());
                    } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                        sbEntity.setSbgrGongs(payDetail.getBubaoPayablePerson());
                    } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                        sbEntity.setSbgrYil(payDetail.getBubaoPayablePerson());
                    } else if ("socialSecurity05".equals(sstype)) {//失业保险
                        sbEntity.setSbgrShiy(payDetail.getBubaoPayablePerson());
                    } else if ("socialSecurity07".equals(sstype)) {//大病保险
                        sbEntity.setSbgrDab(payDetail.getBubaoPayablePerson());
                    } else if ("socialSecurity08".equals(sstype)) {//公积金
                        sbEntity.setSbgrGongjjZc(payDetail.getBubaoPayablePerson());
                    }
                } else {
                    if ("socialSecurity01".equals(sstype)) {//养老保险
                        //单位/个人养老管理 应收费用 由社保缴付明细表中单位应缴-单位付款
                        sbEntity.setSbbcYangl(payDetail.getBalancePayablePerson());
                    } else if ("socialSecurity03".equals(sstype)) {//工伤保险
                        sbEntity.setSbbcGongs(payDetail.getBalancePayablePerson());
                    } else if ("socialSecurity04".equals(sstype)) {//医疗保险
                        sbEntity.setSbbcYil(payDetail.getBalancePayablePerson());
                    } else if ("socialSecurity05".equals(sstype)) {//失业保险
                        sbEntity.setSbbcShiy(payDetail.getBalancePayablePerson());
                    }
                }
            }
            sbEntity.setId(i);
            i++;
            res.add(sbEntity);
        }
        Map<String, Object> result = new HashMap<>();
        result.put("list", res);
        result.put("index", i);
        return result;
    }

    /**
     * 数组分组
     *
     * @param tlist
     * @return
     */
    public Map<String, List<SocialSecurityPayDetailEntity>> groupArray(List<SocialSecurityPayDetailEntity> tlist) {
        Map<String, List<SocialSecurityPayDetailEntity>> m = new HashMap<>();
        for (SocialSecurityPayDetailEntity pay : tlist) {
            String name = pay.getYear() + "-" + pay.getMonth() + "-" + pay.getEmpid();
            if (m.containsKey(name)) {
                m.get(name).add(pay);
            } else {
                List<SocialSecurityPayDetailEntity> list = new ArrayList<>();
                list.add(pay);
                m.put(name, list);
            }
        }
        return m;
    }

    @Override
    @Transactional
    public void saveSalary(JSONArray jsonArray){
        for (Object o : jsonArray) {
            JSONObject obj = (JSONObject) o;
            SalaryBasicinfoEntity sbDetail = obj.toJavaObject(SalaryBasicinfoEntity.class);
            sbDetail.setId(null);

            salaryBasicinfoDao.saveByDynamicCol(sbDetail);
        }
    }

    @Override
    public Map<String, Object> getListInfo(String[] types){
        Map<String, Object> map = new HashMap<>();
        for (String selectInfo : types) {
            map.put(selectInfo,empBaseinfoDao.getSelectInfo(selectInfo));
        }
        List<Map<String, Object>> list = personDispatchDao.getSbList();
        map.put("bxxq",list);
        return map;
    }

    @Override
    public Map<String, Object> getSysOffice(){
        Map<String, Object> map = new HashMap<>();
        List<Map<String, Object>> list = personDispatchDao.getSysOffice();
        map.put("sysOfficeList",list);
        return map;
    }
}
